import csv

OpcTab = []
def InitOpcTab():
    # Read in Opcode Table

    f = open("Opcode Table.csv")
    csvf = csv.reader(f)
    next(csvf)

    for sample in csvf:
        OpcTab.append(sample)

    f.close()

# Open Trace File

InitOpcTab()

f = open("trace.csv")
csvf = csv.reader(f)

# Skip to header

next(csvf)
next(csvf)
next(csvf)
next(csvf)

# Parse Header
# Time(s), /IRQ, R/W, /CS, D6, RS3, RS2, SYNC, RDY, D7, PHi2, D4, D5, D3, D2, D1, D0

sample = next(csvf)
iD0 = sample.index(' D0')
iD1 = sample.index(' D1')
import csv
iD2 = sample.index(' D2')
iD3 = sample.index(' D3')
iD4 = sample.index(' D4')
iD5 = sample.index(' D5')
iD6 = sample.index(' D6')
iD7 = sample.index(' D7')
iSYNC = sample.index(' SYNC')
iRW = sample.index(' R/W')
iRDY = sample.index(' RDY')
iPHI2 = sample.index(' PHI2')

# Initialize the loop

output = open("trace.txt", 'w')
phi2 = '0'
have_op = False
line = ''
sync = True
rw = True
rw_cnt = 0

# Loop over the samples, assembling line to print

for sample in csvf:

    # Process based on Phi2, RDY and R/W
    # Capture control lines when Phi2 is high (provided RDY is high or R/W is low)
    # Process the sample when Phi2 transitions low (provided RDY is high or RW is low)

    pv_phi2 = phi2
    phi2 = sample[iPHI2]
    if phi2 == '1':
        if sample[iRDY] == '1' or sample[iRW] == '0':
            rw = (sample[iRW] == '1')
            sync = (sample[iSYNC] == '1')
        continue

    elif pv_phi2 == '0':
        continue

    elif sample[iRDY] == '0' and sample[iRW] == '1':
        continue

    # Grab the Data Bus on the phi2 edge -- convert to 2 digit hex string

    dbs = '0b'+sample[iD7]+sample[iD6]+sample[iD5]+sample[iD4]+sample[iD3]+sample[iD2]+sample[iD1]+sample[iD0]
    d = int(dbs, 2)
    h = hex(d)[2:]
    if len(h) == 1:
        h = '0' + h

    # get the time

    time = sample[0] + '\t'
    if len(time) < 9:
        time = time + "\t"

    # three write cycles is an interrupt

    if rw:
        rw_cnt =0
    else:
        rw_cnt += 1

    # SYNC cycle -- if sync was high in previous cycle
    # --> output the line if we have an opcode from before, and grab the next opcode data

    if sync:
        if have_op:
            output.write(line + '\n')
        line = time + OpcTab[d][1] + ' ' + OpcTab[d][2] + ' '
        have_op = True
        continue

    # Otherwise accumulate the line

    if rw:
        line = line + ' ' + h
    else:
        line = line + ' (' + h + ')'
        if rw_cnt == 3:
            line = line + " *** \n" + time + "INT ***   "

f.close()
output.close()

#    t = float(sample[0])
#    delta = t - pt
#    print(t)
#    if (delta) > 0.00000021:
#        print(delta)
#    pt = t



